<script >
import { ref,watch,defineComponent, toRefs, reactive, onMounted,onBeforeUnmount  } from 'vue';
import Sidebar from '../common/Sidebar.vue';
import Header from '../common/Header.vue';
import * as echarts from 'echarts';
import axios from "axios";
import 'echarts-liquidfill';
import {Plus} from "@element-plus/icons-vue";


export default defineComponent({
  name: "Attraction",
  components: {
    Plus,
    Sidebar,
    Header,
  },
  data() {
    return {
      attractionID: null,
      attractionName: null,
      attractionScore: null,
      attractionMaxCapacity: null,
      attractionParkingLotCapacity: null,
      attractionLocation: null,
      attractionVisitorCount: null,
      attractionAvailableParkingSpaces:null,
      humanList: [], // 人员列表
      vehicleList: [], // 车辆列表
      staffList: [],
      timer: null,
      editingStaffRow: null,
      editingVehicleRow: null,
      editingHumanRow: null,
      activeName: 'first',
    };
  },
  watch: {
    // 监听searchQuery的变化
    activeName(newValue, oldValue) {
      // 当searchQuery的值变化时，调用这个函数
      // 你可以在这里执行任何你需要的逻辑
      this.initMap();
    },
  },
  mounted() {
    // 在组件挂载时发送请求获取商品信息

    this.fetchAttractionDetail();
    this.fetchHumanList();
    this.fetchVehicleList();
    this.fetchStaffList();
    this.startTimer();

  },
  beforeUnmount() {
    this.stopTimer(); // 在组件卸载前停止定时器
    // ... 其他卸载前的清理逻辑 ...
  },
  methods: {

    initMap(){
      var map = new BMap.Map("mapContainer");
      var defaultPoint = new BMap.Point(116.404, 39.915);
      map.centerAndZoom(defaultPoint, 15);
      var address = '"'+this.attractionName+ '"';
      var attractionLocation = '"'+this.attractionLocation+ '"';
      console.log(attractionLocation);
      var geocoder = new BMap.Geocoder();
      geocoder.getPoint(address, function(point){
        if (point) {
          // 设置地图中心点
          map.centerAndZoom(point, 14);
        } else {
          alert("未找到该地址的经纬度信息！");
        }
      }, attractionLocation); // 可选：设置城市以精确查询

// 启用地图拖拽
      map.enableDragging();
      map.enableScrollWheelZoom(true);
    },

    async deleteStaff(id){
      console.log(id);
      await axios.get(`http://localhost:8081/deletestaff?id=${id}`);
      this.fetchStaffList();
    },
    async deleteHuman(id){
      await axios.get(`http://localhost:8081/deleteemergencyRescuePerson?id=${id}`);
      this.fetchHumanList();
    },
    async deleteVehicle(id){
      await axios.get(`http://localhost:8081/deleteemergencyRescueVehicle?id=${id}`);
      this.fetchVehicleList();
    },

    addStaffRow() {
      const newRow = {
        id: this.staffList.length > 0 ? this.staffList[this.staffList.length-1].id+1 : this.$route.params.id*100+this.staffList.length,// 根据实际情况，可能需要生成一个唯一的ID
        name: '空',
        role: '空',
        contactInfo: '空',
        scenicAreaID: this.$route.params.id,
      };
      this.staffList.push(newRow);
      this.editingStaffRow = this.staffList.length-1;
      axios.post(`http://localhost:8081/insertstaff`, {
        id: newRow.id,
      }, {
        headers: {
          'Content-Type':'application/json',
        },
      })
    },

    addHumanRow() {
      const newRow = {
        id: this.humanList.length > 0 ? this.humanList[this.humanList.length-1].id+1 : this.$route.params.id*100+this.humanList.length,// 根据实际情况，可能需要生成一个唯一的ID
        name: '空',
        qualification: '空',
        contactInfo: '空',
        scenicAreaID: this.$route.params.id,
      };
      this.humanList.push(newRow);
      this.editingHumanRow = this.humanList.length-1;
      axios.post(`http://localhost:8081/insertemergencyRescuePerson`, {
        id: newRow.id,
      }, {
        headers: {
          'Content-Type':'application/json',
        },
      })
    },

    addVehicleRow() {
      const newRow = {
        id: this.vehicleList.length > 0 ? this.vehicleList[this.vehicleList.length-1].id+1 : this.$route.params.id*100+this.vehicleList.length,// 根据实际情况，可能需要生成一个唯一的ID
        licensePlateNumber: '空',
        vehicleType: '空',
        capacity: '空',
        status: '空',
        scenicAreaID: this.$route.params.id,
      };
      this.vehicleList.push(newRow);
      this.editingVehicleRow = this.vehicleList.length-1;
      axios.post(`http://localhost:8081/insertemergencyRescueVehicle`, {
        id: newRow.id,
      }, {
        headers: {
          'Content-Type':'application/json',
        },
      })
    },

    handleStaffEdit(index) {
      this.editingStaffRow = index;
    },
    handleVehicleEdit(index) {
      this.editingVehicleRow = index;
    },
    handleHumanEdit(index) {
      this.editingHumanRow = index;
    },
    async handleStaffEditEnd(index) {
      // 可以在这里添加保存逻辑
      this.editingStaffRow = null;
      await axios.post("http://localhost:8081/updatestaff", {id: this.staffList[index].id,
        name: this.staffList[index].name,
        role: this.staffList[index].role,
        contactInfo: this.staffList[index].contactInfo,
        scenicAreaID : this.staffList[index].scenicAreaID,
      },{headers: {
        'Content-Type':'application/json',
      },})
          .then(response => {
            // 请求成功，处理响应
            console.log('员工信息更新成功', response.data);
            // 你可以在这里根据响应更新UI或进行其他操作
          })
          .catch(error => {
            // 请求失败，处理错误
            if (error.response) {
              // 服务器返回了错误信息
              console.error('更新员工信息失败:', error.response.data);
            } else if (error.request) {
              // 请求已经发起，但没有收到响应
              console.error('请求已发送，但没有收到响应');
            } else {
              // 设置请求时触发了错误
              console.error('请求配置中发生错误');
            }
            // 在这里可以添加一些额外的错误处理逻辑，比如通知用户
          });

      console.log(this.staffList[index]);
    },

    async handleVehicleEditEnd(index) {
      // 可以在这里添加保存逻辑
      this.editingVehicleRow = null;
      await axios.post("http://localhost:8081/updateemergencyRescueVehicle", {id: this.vehicleList[index].id,
        capacity: this.vehicleList[index].capacity,
        status: this.vehicleList[index].status,
        scenicAreaID: this.vehicleList[index].scenicAreaID,
        vehicleType : this.vehicleList[index].vehicleType,
        licensePlateNumber : this.vehicleList[index].licensePlateNumber,
      },{headers: {
          'Content-Type':'application/json',
        },})
          .then(response => {
            // 请求成功，处理响应
            console.log('员工信息更新成功', response.data);
            // 你可以在这里根据响应更新UI或进行其他操作
          })
          .catch(error => {
            // 请求失败，处理错误
            if (error.response) {
              // 服务器返回了错误信息
              console.error('更新员工信息失败:', error.response.data);
            } else if (error.request) {
              // 请求已经发起，但没有收到响应
              console.error('请求已发送，但没有收到响应');
            } else {
              // 设置请求时触发了错误
              console.error('请求配置中发生错误');
            }
            // 在这里可以添加一些额外的错误处理逻辑，比如通知用户
          });

      console.log(this.staffList[index]);
    },

    async handleHumanEditEnd(index) {
      // 可以在这里添加保存逻辑
      this.editingHumanRow = null;
      await axios.post("http://localhost:8081/updateemergencyRescuePerson", {id: this.humanList[index].id,
        name: this.humanList[index].name,
        qualification: this.humanList[index].qualification,
        contactInfo: this.humanList[index].contactInfo,
        scenicAreaID : this.humanList[index].scenicAreaID,
      },{headers: {
          'Content-Type':'application/json',
        },})
          .then(response => {
            // 请求成功，处理响应
            console.log('员工信息更新成功', response.data);
            // 你可以在这里根据响应更新UI或进行其他操作
          })
          .catch(error => {
            // 请求失败，处理错误
            if (error.response) {
              // 服务器返回了错误信息
              console.error('更新员工信息失败:', error.response.data);
            } else if (error.request) {
              // 请求已经发起，但没有收到响应
              console.error('请求已发送，但没有收到响应');
            } else {
              // 设置请求时触发了错误
              console.error('请求配置中发生错误');
            }
            // 在这里可以添加一些额外的错误处理逻辑，比如通知用户
          });

      console.log(this.humanList[index].qualification);
    },

    startTimer() {
      // 设置定时器，假设我们每秒钟调用一次 updateSomething 方法
      this.timer = setInterval(() => {
        this.fetchAttractionDetail();
      }, 15000);
    },
    stopTimer() {
      // 清除定时器
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null; // 将 timer 设置为 null，表示没有定时器在运行
      }
    },
    fetchAttractionDetail() {
      console.log(this.$route.params.id);
      axios.get(`http://localhost:8081/searchscenicSpotByID?id=${this.$route.params.id}`)
          .then(response => {
            this.attractionID = response.data.id;
            this.attractionName = response.data.name;
            this.attractionScore = response.data.score;
            this.attractionLocation = response.data.geographicLocation;
            this.attractionMaxCapacity = response.data.maxCapacity;
            this.attractionParkingLotCapacity = response.data.parkingLotCapacity;
            let letters = response.data.electronicMapURL.split(",");
            this.updateChart();
          })
          .catch(error => {
            console.error('获取景区详情失败:', error);
          });

      axios.get(`http://localhost:8081/searchrealtimeInfoByID?id=${this.$route.params.id}`)
          .then(response => {
            this.attractionVisitorCount = response.data.visitorCount;
            this.attractionAvailableParkingSpaces = response.data.availableParkingSpaces;
            this.updateChart();
          })
    },
    fetchHumanList() {
      console.log(this.$route.params.id);
      axios.get(`http://localhost:8081/selectemergencyRescuePersonbyscenicareaid?scenicareaid=${this.$route.params.id}`)
          .then(response => {
            this.humanList = response.data; // 假设你有一个 hotelDetail 数据属性来存储单个酒店的详情
            console.log(this.humanList);
          })
          .catch(error => {
            console.error('获取人员详情失败:', error);
          });
    },
    fetchVehicleList() {
      console.log(this.$route.params.id);
      axios.get(`http://localhost:8081/selectemergencyRescueVehiclebyscenicareaid?scenicareaid=${this.$route.params.id}`)
          .then(response => {
            this.vehicleList = response.data; // 假设你有一个 hotelDetail 数据属性来存储单个酒店的详情
            console.log(this.vehicleList);
          })
          .catch(error => {
            console.error('获取人员详情失败:', error);
          });
    },
    fetchStaffList() {
      console.log(this.$route.params.id);
      axios.get(`http://localhost:8081/selectstaffbyscenicareaid?scenicareaid=${this.$route.params.id}`)
          .then(response => {
            this.staffList = response.data; // 假设你有一个 hotelDetail 数据属性来存储单个酒店的详情
            console.log(this.vehicleList);
          })
          .catch(error => {
            console.error('获取人员详情失败:', error);
          });
    },
    updateChart() {
      const capacity = this.attractionVisitorCount || 0; // 使用默认值防止未定义
      const maxcapacity = this.attractionMaxCapacity || 0;
      const parking = this.attractionAvailableParkingSpaces || 0;
      const maxparking = this.attractionParkingLotCapacity || 0;
      const score = this.attractionScore || 0;
      let color;
      if(capacity/maxcapacity<0.3){
        color = '#3f9f48'
      }
      else if(capacity/maxcapacity>0.7){
        color = '#e93540'
      }
      else {
        color = '#FFFF00'
      }
      const option1 = {
        series: [{
          data: [
            {
              value: capacity,
            },
            {
              value: maxcapacity - capacity,
              name: undefined
            }
          ],
          color: [color, '#d3d3d3'],
        }]
      };
      const option2 = {
        series: [{
          data: [
            {
              value: parking,
            },
            {
              value: maxparking - parking,
              name: undefined
            }
          ]
        }]
      };
      const option3 = {
        series: [{
          data: [score/100, score/100-0.1, score/100-0.2, score/100-0.3],
        }]
      };
      const myChart = echarts.init(document.getElementById('myChart'));
      myChart.setOption(option1);
      const secondChart = echarts.init(document.getElementById('secondChart'));
      secondChart.setOption(option2);
      const reputationChart = echarts.init(document.getElementById('reputationChart'));
      reputationChart.setOption(option3);
      console.log(score);
    },
  },


  setup() {
    const activeName = ref('first');

    const handleClick = (tab, event) => {
      console.log(tab, event);
    };
    const state = reactive({
      option3: {
        series: [
          {
            type: "liquidFill",
            data: [0.6, 0.5, 0.4, 0.3],
            itemStyle: {
              normal: {
                shadowBlur: 0,
              },
            },
            outline: {
              borderDistance: 0,
              itemStyle: {
                borderWidth: 5,
                borderColor: "#156ACF",
                shadowBlur: 20,
                shadowColor: "#156ACF",
              },
            },
          },
        ],
      },
      option1: {
        title: {
          text: '接待量',
          left: 'center',
          top: 'center'
        },
        series: [
          {
            type: 'pie',
            data: [
              {
                value: 0,
              },
              {
                value: 0,
                name: undefined
              }
            ],
            radius: ['40%', '70%'],
            color: ['#e93540', '#d3d3d3'],
            labelLine: {
              show: false // 隐藏引导线
            },
            label: {
              show: true, // 显示标签
              formatter: '{d}%', // 格式化标签为百分比
              position: 'inside',
            }
          },
        ],
      },
      option2: {
        title: {
          text: '停车位数量',
          right: 'center',
          top: 'center'
        },
        series: [
          {
            type: 'pie',
            data: [
              {
                value: 0,
              },
              {
                value: 0,
                name: undefined
              }
            ],
            radius: ['40%', '70%'],
            color: ['#3f9f48', '#e93540'],
            labelLine: {
              show: false // 隐藏引导线
            },
            label: {
              show: true, // 显示标签
              formatter: '{d}%', // 格式化标签为百分比
              position: 'inside'
            }
          },
        ],
      },

    });
    let timer;
    const initeCharts = () => {
      let myChart = echarts.init(document.getElementById('myChart'))
      // 绘制图表
      myChart.setOption(state.option1)
    }
    const initSecondChart = () => {
      let secondChart = echarts.init(document.getElementById('secondChart'))
      // 绘制第二个图表
      secondChart.setOption(state.option2)
    }
    const reputationChart = () => {
      let reputationChart = echarts.init(document.getElementById('reputationChart'))
      // 绘制第二个图表
      reputationChart.setOption(state.option3)

    }

    onMounted(() => {
      reputationChart();
      initeCharts();
      initSecondChart();
    });
    return {
      state,
      ...toRefs(state),
      activeName,
      handleClick,
    };
  },

});

</script>


<template>

  <body>
  <el-col style="height: 100vh;">
    <Header />
    <el-row style="height: 100%;">
      <el-col :span="3" style="height: 100vh;">
        <Sidebar />
      </el-col>
      <el-col :span="21" style="height: 800px; overflow: scroll">
        <el-tabs v-model="activeName" class="demo-tabs"  @tab-click="handleClick" style="height: 100%;width: 100%" >
          <el-tab-pane label="管理信息" name="first" >
            <el-col span="12" style="width: 100%;text-align: center;background-color: #f7f7f7">

              <el-row style="background-color: #f7f7f7;text-align: center;display: flex;justify-content: center">
                <el-col :span="8" >
                  <div id="reputationChart" style="background-color: white; width: 300px; height: 300px;margin: 30px;border-radius: 80px;margin-left: 80px"></div>
                    <h2 :style="{ marginRight:'10px'}">信誉积分</h2>
                </el-col>
                <el-col :span="8"><div id="myChart" :style="{ width: '300px', height: '300px', margin: '30px',backgroundColor:'#fff',borderRadius:'80px',marginLeft:'80px'}"></div></el-col>
                <el-col :span="8"><div id="secondChart" :style="{ width: '300px', height: '300px', margin: '30px',backgroundColor:'#fff',borderRadius:'80px', marginLeft:'80px'}"></div></el-col>
              </el-row>

              <el-row style="margin-top: 30px;margin-bottom: 50px">
                <el-col :span="8"><label class="lbl-hotel">景区ID:{{this.attractionID}}</label></el-col>
                <el-col :span="8"><label class="lbl-hotel">景区名:{{this.attractionName}}</label></el-col>
                <el-col :span="8"><label class="lbl-hotel">位置:{{this.attractionLocation}}</label></el-col>
              </el-row>
              <el-card style="margin-left: 80px;margin-bottom: 30px;margin-right: 80px">
                <template #header>
                  <h1>管理人员</h1>
                </template>
              <el-table :data="staffList" stripe  height="250"  style="margin: 30px;width: 1430px" >
                <el-table-column fixed prop="id" label="管理人员编号" width="120" align="center"/>
                <el-table-column prop="name" label="姓名" width="120" align="center">
                  <template v-slot="scope">
                    <!-- 使用作用域插槽的 scope.row 来访问当前行的数据 -->
                    <el-input v-if="editingStaffRow === scope.$index" v-model="scope.row.name" @blur="handleStaffEditEnd(scope.$index)"></el-input>
                    <div v-else @click="handleStaffEdit(scope.$index)">
                      {{ scope.row.name }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="role" label="职位" width="120" align="center">
                  <template v-slot="scope">
                    <!-- 使用作用域插槽的 scope.row 来访问当前行的数据 -->
                    <el-input v-if="editingStaffRow === scope.$index" v-model="scope.row.role" @blur="handleStaffEditEnd(scope.$index)"></el-input>
                    <div v-else @click="handleStaffEdit(scope.$index)">
                      {{ scope.row.role }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="contactInfo" label="联系电话" width="120" align="center">
                  <template v-slot="scope">
                    <!-- 使用作用域插槽的 scope.row 来访问当前行的数据 -->
                    <el-input v-if="editingStaffRow === scope.$index" v-model="scope.row.contactInfo" @blur="handleStaffEditEnd(scope.$index)"></el-input>
                    <div v-else @click="handleStaffEdit(scope.$index)">
                      {{ scope.row.contactInfo }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" min-width="100" align="center">
                  <template #default="scope">
                    <el-button link type="primary" @click="deleteStaff(scope.row.id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
                <template #footer><el-button color="#9d2933" circle size="large" plain @click="addStaffRow" ><el-icon><plus/></el-icon></el-button></template>
              </el-card>
              <el-card style="margin-left: 80px;margin-bottom: 30px;margin-right: 80px">
                <template #header>
                  <h1>应急救援车辆信息</h1>
                </template>
              <el-table :data="vehicleList" stripe  height="250"  style="margin: 30px;width: 1430px" >
                <el-table-column fixed prop="id" label="应急车辆编号" width="120" align="center"/>
                <el-table-column prop="licensePlateNumber" label="车牌号" width="120" align="center">
                  <template v-slot="scope">
                    <!-- 使用作用域插槽的 scope.row 来访问当前行的数据 -->
                    <el-input v-if="editingVehicleRow === scope.$index" v-model="scope.row.licensePlateNumber" @blur="handleVehicleEditEnd(scope.$index)"></el-input>
                    <div v-else @click="handleVehicleEdit(scope.$index)">
                      {{ scope.row.licensePlateNumber }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="vehicleType" label="车辆类型" width="120" align="center">
                  <template v-slot="scope">
                    <!-- 使用作用域插槽的 scope.row 来访问当前行的数据 -->
                    <el-input v-if="editingVehicleRow === scope.$index" v-model="scope.row.vehicleType" @blur="handleVehicleEditEnd(scope.$index)"></el-input>
                    <div v-else @click="handleVehicleEdit(scope.$index)">
                      {{ scope.row.vehicleType }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="capacity" label="承载量" width="120" align="center">
                  <template v-slot="scope">
                    <!-- 使用作用域插槽的 scope.row 来访问当前行的数据 -->
                    <el-input v-if="editingVehicleRow === scope.$index" v-model="scope.row.capacity" @blur="handleVehicleEditEnd(scope.$index)"></el-input>
                    <div v-else @click="handleVehicleEdit(scope.$index)">
                      {{ scope.row.capacity }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="车辆状态" width="120" align="center">
                  <template v-slot="scope">
                    <!-- 使用作用域插槽的 scope.row 来访问当前行的数据 -->
                    <el-input v-if="editingVehicleRow === scope.$index" v-model="scope.row.status" @blur="handleVehicleEditEnd(scope.$index)"></el-input>
                    <div v-else @click="handleVehicleEdit(scope.$index)">
                      {{ scope.row.status }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" min-width="100" align="center">
                  <template #default="scope">
                    <el-button link type="primary" @click="deleteVehicle(scope.row.id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
                <template #footer><el-button color="#9d2933" circle size="large" plain @click="addVehicleRow" ><el-icon><plus/></el-icon></el-button></template>
              </el-card>
              <el-card style="margin-left: 80px;margin-bottom: 30px;margin-right: 80px">
                <template #header>
                  <h1>应急救援人员信息</h1>
                </template>
              <el-table :data="humanList" stripe  height="250"  style="margin: 30px;width: 1430px" >
                <el-table-column fixed prop="id" label="应急人员编号" width="120" align="center"/>
                <el-table-column prop="name" label="姓名" width="120" align="center">
                  <template v-slot="scope">
                    <!-- 使用作用域插槽的 scope.row 来访问当前行的数据 -->
                    <el-input v-if="editingHumanRow === scope.$index" v-model="scope.row.name" @blur="handleHumanEditEnd(scope.$index)"></el-input>
                    <div v-else @click="handleHumanEdit(scope.$index)">
                      {{ scope.row.name }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="qualification" label="资质" width="120" align="center">
                  <template v-slot="scope">
                    <!-- 使用作用域插槽的 scope.row 来访问当前行的数据 -->
                    <el-input v-if="editingHumanRow === scope.$index" v-model="scope.row.qualification" @blur="handleHumanEditEnd(scope.$index)"></el-input>
                    <div v-else @click="handleHumanEdit(scope.$index)">
                      {{ scope.row.qualification }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="contactInfo" label="联系电话" width="120" align="center">
                  <template v-slot="scope">
                    <!-- 使用作用域插槽的 scope.row 来访问当前行的数据 -->
                    <el-input v-if="editingHumanRow === scope.$index" v-model="scope.row.contactInfo" @blur="handleHumanEditEnd(scope.$index)"></el-input>
                    <div v-else @click="handleHumanEdit(scope.$index)">
                      {{ scope.row.contactInfo }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" min-width="100" align="center">
                  <template #default="scope">
                    <el-button link type="primary" @click="deleteHuman(scope.row.id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
                <template #footer><el-button color="#9d2933" circle size="large" plain @click="addHumanRow" ><el-icon><plus/></el-icon></el-button></template>
              </el-card>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="电子地图" name="second" >
              <div id="mapContainer" style="width: 100%; height: 850px;"></div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </el-col>
  </body>
</template>

<style scoped>
@import "../../assets/css/global.css";
</style>